// src/utils/storage.ts
export interface User {
  account: string
  nickname: string
  password: string
}

const USERS_KEY = 'chat-demo-users'
const CURRENT_KEY = 'chat-demo-currentUser'

/** 读取所有用户 */
export function getUserList(): User[] {
  const raw = localStorage.getItem(USERS_KEY)
  return raw ? JSON.parse(raw) : []
}

/** 添加新用户，账号已存在则返回 false */
export function addUser(user: User): boolean {
  const list = getUserList()
  if (list.some(u => u.account === user.account)) {
    return false
  }
  list.push(user)
  localStorage.setItem(USERS_KEY, JSON.stringify(list))
  return true
}

/** 获取当前登录用户，若无则返回 null */
export function getCurrentUser(): User | null {
  const raw = localStorage.getItem(CURRENT_KEY)
  return raw ? JSON.parse(raw) : null
}

/** 设置当前登录用户 */
export function setCurrentUser(user: User): void {
  localStorage.setItem(CURRENT_KEY, JSON.stringify(user))
}

/** 退出登录 */
export function clearCurrentUser(): void {
  localStorage.removeItem(CURRENT_KEY)
}
